<template>
  <a-modal
    :width="modalWidth"
    :visible="visible"
    :title="title"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="取消"
  >
    <!-- 操作按钮区域 -->
    <div class="table-operator" v-if="!isAll">
      <a-button type="success" icon="plus" v-has="'device:edit'" @click="showAddModal('MealManageRef')"
        >新增套餐</a-button
      >
    </div>
    <!-- table区域 -->
    <a-table
      ref="table"
      bordered
      size="middle"
      rowKey="id"
      :columns="columns"
      :dataSource="dataSource"
      :pagination="ipagination"
      :loading="loading"
      :scroll="{ x: 1200 }"
      @change="handleTableChange"
    >
      <template
        v-for="col in ['timesPrice', 'fixedPrice', 'prepaidAmount', 'freeTime', 'maxAmount', 'maxChargingTime']"
        :slot="col"
        slot-scope="text, record, index"
      >
        <div :slot="col">
          <a-input-number
            v-if="record.isEdit"
            style="margin: -5px 0"
            placeholder="请输入"
            :value="text"
            @change="e => handleChange(e, record, col, index)"
          />
          <template v-else>
            {{ text }}
          </template>
        </div>
      </template>

      <template slot="maxServiceTime" slot-scope="text, record, index">
        <a-time-picker
          v-if="record.isEdit"
          class="per100"
          format="HH:mm"
          valueFormat="HH:mm"
          style="margin: -5px 0"
          placeholder="请输入"
          :value="text"
          @change="e => handleChange(e, record, 'maxServiceTime', index)"
        />
        <template v-else>
          {{ text }}
        </template>
      </template>

      <template v-for="item in ['remark', 'apkRemark']" :slot="item" slot-scope="text, record, index">
        <div :slot="item">
          <a-textarea
            v-if="record.isEdit"
            style="margin: -5px 0"
            placeholder="请输入"
            :value="text"
            @change="e => handleTextareaChange(e, record, item, index)"
          />
          <template v-else>
            {{ text }}
          </template>
        </div>
      </template>

      <span slot="action" slot-scope="text, record, index">
        <span v-if="record.isEdit">
          <a-button type="success" size="small" class="ml5 mr5" @click="() => save(record, index)">保存</a-button>
          <a-popconfirm title="确定要取消吗？" @confirm="() => cancel(record, index)">
            <a-button size="small" class="ml5 mr5">取消</a-button>
          </a-popconfirm>
        </span>
        <span v-else>
          <a-button type="primary" size="small" class="ml5 mr5" @click="() => edit(record, index)">编辑</a-button>
          <a-popconfirm title="确定要删除该套餐吗？" v-if="!isAll" @confirm="onDelete(record, index)">
            <a-button type="danger" size="small" class="ml5 mr5">删除</a-button>
          </a-popconfirm>
        </span>
      </span>
    </a-table>

    <!-- 套餐管理 -->
    <meal-manage ref="MealManageRef" @close="modalOk"></meal-manage>
  </a-modal>
</template>

<script>
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { initDictOptions, filterDictText } from '@/components/dict/JDictSelectUtil'
import { httpAction, deleteAction } from '@/api/manage'
import Api from '@/api/DeviceManage/DeviceList'
import { cloneObject, formatAmountFromFenToYuan } from '@/utils/util'
import MealManage from './MealManage'

export default {
  name: 'MealManage',
  mixins: [JeecgListMixin],
  components: { MealManage },
  data() {
    return {
      filterDictText,
      title: '套餐管理',
      modalWidth: '70%',
      visible: false,
      url: {
        list: Api.mealList
      },
      columns: [],
      disableMixinCreated: true,
      cellTypeOptions: [],
      isAll: false, // 是否批量修改
      ids: [] // 批量修改ids
    }
  },
  created() {
    this.columns = [
      {
        title: '格子类型',
        dataIndex: 'cellType',
        customRender: (text, record, index) => {
          //字典值替换通用方法
          return filterDictText(this.cellTypeOptions, text)
        }
      },
      {
        title: '按次价格（元/次）',
        dataIndex: 'timesPrice',
        scopedSlots: { customRender: 'timesPrice' }
      },
      {
        title: '固定收费（元/小时）',
        dataIndex: 'fixedPrice',
        scopedSlots: { customRender: 'fixedPrice' }
      },
      {
        title: '预付金额（元）',
        dataIndex: 'prepaidAmount',
        scopedSlots: { customRender: 'prepaidAmount' }
      },
      {
        title: '免费使用时间（分钟）',
        dataIndex: 'freeTime',
        scopedSlots: { customRender: 'freeTime' }
      },
      {
        title: '上限金额（元）',
        dataIndex: 'maxAmount',
        scopedSlots: { customRender: 'maxAmount' }
      },
      {
        title: '计费封顶时间（小时）',
        dataIndex: 'maxChargingTime',
        scopedSlots: { customRender: 'maxChargingTime' }
      },
      {
        title: '最大服务时间',
        dataIndex: 'maxServiceTime',
        scopedSlots: { customRender: 'maxServiceTime' }
      },
      {
        title: '备注',
        dataIndex: 'remark',
        scopedSlots: { customRender: 'remark' }
      },
      {
        title: '安卓文本备注',
        dataIndex: 'apkRemark',
        scopedSlots: { customRender: 'apkRemark' }
      },
      {
        title: '操作',
        dataIndex: 'action',
        width: 140,
        scopedSlots: { customRender: 'action' }
      }
    ]
    this.initDictConfig()
  },
  methods: {
    // 初始化数据字典
    initDictConfig() {
      //初始化字典 - 格子类型
      initDictOptions('cellType').then(res => {
        if (res.success) {
          this.cellTypeOptions = res.result
        }
      })
    },

    // 展示弹窗
    async showModal(record, data) {
      this.visible = true
      if (record === 'setMeal') {
        // 批量修改套餐
        this.ids = data
        this.isAll = true
      } else {
        this.isAll = false
        this.queryParam.deviceId = record.deviceId
      }
      this.searchData()
    },

    async searchData() {
      await this.loadData()
      this.dataSource = this.dataSource.map(item => {
        const obj = item
        obj.isEdit = false
        obj.timesPrice = formatAmountFromFenToYuan(obj.timesPrice || '')
        obj.fixedPrice = formatAmountFromFenToYuan(obj.fixedPrice || '')
        obj.prepaidAmount = formatAmountFromFenToYuan(obj.prepaidAmount || '')
        obj.maxAmount = formatAmountFromFenToYuan(obj.maxAmount || '')
        return obj
      })
      this.cacheData = JSON.parse(JSON.stringify(this.dataSource))
    },

    async handleTableChange(pagination, filters, sorter) {
      //分页、排序、筛选变化时触发
      //TODO 筛选
      if (Object.keys(sorter).length > 0) {
        this.isorter.column = sorter.field
        this.isorter.order = 'ascend' == sorter.order ? 'asc' : 'desc'
      }
      this.ipagination = pagination
      await this.loadData()
      this.cacheData = JSON.parse(JSON.stringify(this.dataSource))
    },
    handleOk() {
      this.loading = true
      let setmealList = cloneObject(this.dataSource)
      setmealList.forEach(record => {
        record.timesPrice = record.timesPrice * 100
        record.fixedPrice = record.fixedPrice * 100
        record.prepaidAmount = record.prepaidAmount * 100
        record.maxAmount = record.maxAmount * 100
      })
      const data = {
        ids: this.isAll ? this.ids : [this.queryParam.deviceId],
        setmealList: setmealList
      }
      httpAction(Api.mealBatchEdit, data, 'put')
        .then(res => {
          if (res.code === 200) {
            this.$message.success(res.message)
            this.searchData()
          } else {
            this.$message.error(res.message)
          }
        })
        .finally(() => {
          this.loading = false
        })
      this.close()
    },
    handleCancel() {
      this.close()
    },
    close() {
      this.$emit('close')
      this.visible = false
      this.queryParam.deviceId = ''
      this.disableSubmit = false
    },

    // input改变
    handleChange(value, record, column, index) {
      record[column] = value
    },
    // textarea改变
    handleTextareaChange(value, record, column, index) {
      record[column] = value.target.value
    },
    // 编辑
    edit(record, index) {
      record.isEdit = true
      this.dataSource.splice(index, 1, record)
    },
    // 保存
    save(record, index) {
      this.$set(this.dataSource[index], 'isEdit', false)
      this.$forceUpdate()
    },
    // 取消
    cancel(record, index) {
      record = JSON.parse(JSON.stringify(this.cacheData[index]))
      this.dataSource.splice(index, 1, record)
    },

    // 删除套餐
    onDelete(record, index) {
      const data = { id: record.id }
      this.loading = true
      deleteAction(Api.mealDelete, data)
        .then(res => {
          if (res.code === 200) {
            this.$message.success(res.message)
            record.isEdit = false
            this.searchData()
          } else {
            this.$message.error(res.message)
          }
        })
        .finally(() => {
          this.loading = false
        })
    },

    // 展示新增套餐弹窗
    showAddModal(name) {
      // 批量修改套餐
      this.$refs[name].showModal('setMeal', [this.queryParam.deviceId])
    },

    modalOk() {
      this.searchData()
    }
  }
}
</script>

